package com.erp.ae.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.erp.ae.domain.AeMsgSave;
import com.erp.ae.domain.AePullOrderErrorLog;
import com.ruoyi.ae.api.domain.AeStoreChildOrder;
import com.ruoyi.ae.api.domain.AeStoreOrder;
import com.ruoyi.ae.api.domain.AeStoreOrderProduct;
import com.ruoyi.ae.api.domain.AeStoreOrderReceiptAddress;
import com.erp.ae.domain.enums.AliExpressInterfaceEnum;
import com.erp.ae.mapper.*;
import com.erp.ae.service.IAeSaveOrderService;
import com.erp.ae.service.IAeStoreOrderService;
import com.global.iop.domain.Protocol;
import com.ruoyi.common.core.domain.R;
import com.erp.ae.utils.AeApiUtils;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.redis.utils.RedisUtils;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import lombok.RequiredArgsConstructor;
import org.jacoco.agent.rt.internal_035b120.core.internal.flow.IFrame;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 商户订单Service业务层处理
 *
 * @author erp
 * @date 2023-03-09
 */
@RequiredArgsConstructor
@Service
public class AeSaveOrderServiceImpl implements IAeSaveOrderService {
    private static final String AE_MSG_KEY = "AE_MSG_ORDER_LIST";

    private final IAeStoreOrderService iAeStoreOrderService;
    private final AeMsgSaveMapper aeMsgSaveMapper;
    private final AePullOrderErrorLogMapper pullOrderErrorLogMapper;

    @Resource
    RemoteSellerStoreService remoteSellerStoreService;

    /**
     * @param storeUserName
     * @param accessToken
     * @param type  0 - 新订单 1-增量订单
     * @return
     * @Description: 根据店铺CN码拉取所有订单
     * @Author: j.zh
     * @Date: 2024/5/9
     * @Version: 4.0.0
     **/
    @Override
    public R<Object> pullOrdersFromAliExpress(String orderIds, String storeUserName, String accessToken,Integer type) {
        List<Long> newOrderIdList = Arrays.asList(Long.parseLong(orderIds));
        // 根据新订单，获取订单详情
        for (Long newOrderId : newOrderIdList) {
            AeStoreOrder newOrder = new AeStoreOrder();
            newOrder.setOrderId(newOrderId);

            JSONObject newOrderDetails = JSONObject.parseObject(
                    AeApiUtils.sendRequest(
                            "aliexpress.trade.new.redefining.findorderbyid",
                            "param1",
                            "{\"order_id\":" + newOrderId + "}",
                            Protocol.TOP,
                            accessToken
                    )
            ).getJSONObject("aliexpress_trade_new_redefining_findorderbyid_response").getJSONObject("target");

            if (type ==0){
                // 3、封装原始订单信息、入库并进行mq分发
                iAeStoreOrderService.saveAeNewOrderInfo(newOrder, newOrderDetails, accessToken);
            }else{
                iAeStoreOrderService.saveAeIncrementalOrderInfo(newOrder,newOrderDetails,accessToken);
            }
        }

        return R.ok("店铺:" + storeUserName + "，本次获取到" + newOrderIdList.size() + "条新订单");
    }

    /**
     * @param storeUserName
     * @param accessToken
     * @param createDateStart
     * @param createDateEnd
     * @return java.util.List<java.lang.Long>
     * @Description: 拉取新订单ID集合
     * @Author: j.zh
     * @Date: 2024/5/9
     * @Version: 4.0.0
     **/
    @Override
    public List<Long> pullNewOrderIdListFromAliExpress(String storeUserName, String accessToken, String createDateStart, String createDateEnd) {
        // 1、获取AE订单
        if (createDateStart == null) {
            //获取五天前的时间
            //当前时间
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 格式化当前时间
            String endFormatted = now.format(formatter);
            LocalDateTime parse = LocalDateTime.parse(endFormatted, formatter);
            LocalDateTime zeroHour = parse.plusDays(-3).withHour(0).withMinute(0).withSecond(0).withNano(0);
            String createFormatted = zeroHour.format(formatter);
            createDateStart = createFormatted;
            createDateEnd = endFormatted;
        }

        String currentPage = "1";
        Integer pageSize = 100;

        // 取到时间区间内的订单
        JSONObject returnOrderList = JSONObject.parseObject(
                AeApiUtils.sendRequest(
                        "aliexpress.trade.seller.orderlist.get",
                        "param_aeop_order_query",
                        "{" +
                                "\"create_date_start\":\"" + createDateStart + "\"," +
                                "\"create_date_end\":\"" + createDateEnd + "\"," +
                                "\"current_page\":\"" + currentPage + "\"," +
                                "\"page_size\":\"" + pageSize + "\"}",
                        Protocol.TOP,
                        accessToken
                )
        );
        if (returnOrderList.toString().contains("error_response")) {
            pullOrderErrorLogMapper.insert(new AePullOrderErrorLog(storeUserName, "获取订单失败", returnOrderList.toString()));
            return null;
        }
        String resultJSON = returnOrderList
                .getJSONObject("aliexpress_trade_seller_orderlist_get_response")
                .getString("result");
        String orderJSON = returnOrderList
                .getJSONObject("aliexpress_trade_seller_orderlist_get_response")
                .getJSONObject("result")
                .getJSONObject("target_list")
                .getString("aeop_order_item_dto");

        JSONArray orderArray = JSONArray.parseArray(orderJSON);
        if (com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNull(orderJSON)) {
            pullOrderErrorLogMapper.insert(new AePullOrderErrorLog(storeUserName, "暂无订单", null));
            return null;
        }

        // 2、有订单，则获取本地订单列表
        List<AeStoreOrder> aeStoreOrderList = iAeStoreOrderService.getListByStoreUserName(storeUserName, createDateStart, createDateEnd);
        List<Long> orderIdList = aeStoreOrderList.stream().map(AeStoreOrder::getOrderId).collect(Collectors.toList());

        // 3、遍历在线订单ID，并进行去重
        List<Long> newOrderIdList = new ArrayList<>();
        for (Object aeStoreOrderObject : orderArray) {
            JSONObject orderObj = (JSONObject) aeStoreOrderObject;
            Long newOrderId = orderObj.getLong("order_id");
            if (!orderIdList.contains(newOrderId)) {
                // 本地没有该订单
                newOrderIdList.add(newOrderId);
            }
        }

        // 4、返回新订单ID
        return newOrderIdList;
    }

    /**
     * ae消息推送订单信息
     *
     * @return
     */
    @Override
    @Transactional
    public R<Object> aePushOrdersInfo(String orderIds) {
        //清除缓存
        RedisUtils.setCacheObject(AE_MSG_KEY,new String());
        List<String> orderIdList = Arrays.asList(orderIds.split(","));
        for (String orderId : orderIdList) {
            //按时间倒序取第一条
            AeMsgSave aeMsgSave = aeMsgSaveMapper.selectOne(
                    new LambdaQueryWrapper<AeMsgSave>()
                            .isNotNull(AeMsgSave::getLoginId)
                            .eq(AeMsgSave::getTradeOrderId, orderId)
                            .orderByDesc(AeMsgSave::getCreateTime)
                            .last("limit 1")
            );
            if (Objects.isNull(aeMsgSave)){
                return R.fail("获取店铺信息为空");
            }
            String token = null;
            try{
                 token = AeApiUtils.getToken(aeMsgSave.getLoginId());
            }catch (Exception e){
                //获取缓存中的商品
                String orderIdOlds = RedisUtils.getCacheObject(AE_MSG_KEY);
                if (orderIdOlds.equals("")){
                    orderIds = orderId;
                }else {
                    orderIds = orderIds + "," + orderId;
                }
                /** 放入redis中 */
                RedisUtils.setCacheObject(AE_MSG_KEY, orderIds);
                continue;
            }

            pullOrdersFromAliExpress(orderId, aeMsgSave.getLoginId(), token,1);
        }
        return R.ok();
    }


    // 4.0.0以后废弃
//    @Override
//    public R<Object> queryOrderFromAeByOrderId(String accessToken, Long orderId) {
//        if (StringUtils.isNotEmpty(accessToken)) {
//
//            AeStoreOrder order = aeStoreOrderMapper.selectByOrderId(orderId);
//            if (ObjectUtils.isEmpty(order)) {
//                order = new AeStoreOrder();
//                order.setOrderId(orderId);
//            }
//
//            //获取订单信息
//            JSONObject orderDetails = JSONObject.parseObject(
//                    AeApiUtils.sendRequest(
//                            AliExpressInterfaceEnum.findOrderById.getCode(),
//                            "param1",
//                            "{\"order_id\":" + orderId + "}",
//                            Protocol.TOP,
//                            accessToken
//                    )
//            ).getJSONObject("aliexpress_trade_new_redefining_findorderbyid_response").getJSONObject("target");
//            //保存订单信息
//            iAeStoreOrderService.saveAeOrderInfo(order, orderDetails, accessToken);
//
//            //返回订单信息
//            return returnErpOrderList(order.getOrderId());
//        } else {
//            return R.fail("店铺未授权");
//        }
//    }


    //填补AeStoreOrder 迁移至AeStoreOrderServiceImpl
//    private AeStoreOrder saveAeStoreOrderByDetails(AeStoreOrder aeStoreOrder, JSONObject orderDetails) {
//        //填补信息
////        aeStoreOrder.setSellerOperatorAliidloginid(orderDetails.getString("seller_operator_aliidloginid"));
//        aeStoreOrder.setSettlementCurrency(orderDetails.getString("settlement_currency"));
//        aeStoreOrder.setCod(orderDetails.getString("cod"));
//        aeStoreOrder.setCancelRequestReason(orderDetails.getString("cancel_request_reason"));
//        // 新订单金额 含税价订单，不含税金
//        JSONObject newOrderAmount = orderDetails.getJSONObject("new_order_amount");
//        aeStoreOrder.setNewOrderAmount(newOrderAmount.getString("amount"));
//        aeStoreOrder.setNewOrderCurrencyCode(newOrderAmount.getString("currency_code"));
//        //  新订单金额
//        JSONObject sellerOrderAmount = orderDetails.getJSONObject("seller_order_amount");
//        aeStoreOrder.setSellerOrderAmount(sellerOrderAmount.getString("amount"));
//        aeStoreOrder.setSellerOrderCurrencyCode(sellerOrderAmount.getString("currency_code"));
//
//        //买家信息
//        JSONObject buyerInfo = orderDetails.getJSONObject("buyer_info");
//        aeStoreOrder.setBuyerCountry(buyerInfo.getString("country"));
//        aeStoreOrder.setBuyerLastName(buyerInfo.getString("first_name"));
//        aeStoreOrder.setBuyerFirstName(buyerInfo.getString("last_name"));
//
//        //订单最后更新时间
//        aeStoreOrder.setGmtTradeEnd(orderDetails.getString("gmt_trade_end"));
//        //订单创建时间
//        aeStoreOrder.setGmtCreate(orderDetails.getString("gmt_create"));
//        //订单支付成功时间
//        String paySuccess = orderDetails.getString("gmt_pay_success");
//        if (paySuccess != null) {
//            aeStoreOrder.setGmtPayTime(paySuccess);
//        }
//        //备注
//        aeStoreOrder.setMemo(orderDetails.getString("memo"));
//        //结束原因
//        aeStoreOrder.setOrderEndReason(orderDetails.getString("order_end_reason"));
//        //买家支付金额(结算币种)
////        JSONObject payAmount = orderDetails.getJSONObject("pay_amount_by_settlement_cur");
////        aeStoreOrder.setPayAmount(payAmount.getString("amount"));
//        //买家支付金额(结算币种)
////        aeStoreOrder.setPayCurrencyCode(payAmount.getString("currency_code"));
//        aeStoreOrder.setPayAmount(orderDetails.getString("pay_amount_by_settlement_cur"));
//        //付款方式 （migs信用卡支付走人民币渠道； migs102MasterCard支付并且走人民币渠道； migs101Visa支付并且走人民币渠道； pp101 PayPal； mb MoneyBooker渠道； tt101 Bank Transfer支付； wu101 West Union支付； wp101 Visa走美金渠道的支付； wp102 Mastercard 走美金渠道的支付； qw101 QIWI支付； cybs101 Visa走CYBS渠道的支付； cybs102 Mastercard 走CYBS渠道的支付； wm101 WebMoney支付； ebanx101 巴西Beloto支付 ；）
//        aeStoreOrder.setPaymentType(orderDetails.getString("payment_type"));
//        //订单金额
//        JSONObject orderAmount = orderDetails.getJSONObject("order_amount");
//        aeStoreOrder.setOrderAmount(orderAmount.getString("amount"));
//        aeStoreOrder.setOrderCent(orderAmount.getBigDecimal("cent"));
//        aeStoreOrder.setOrderCentFactor(orderAmount.getLong("cent_factor"));
//        //货币描述
//        JSONObject orderCurrency = orderAmount.getJSONObject("currency");
//        aeStoreOrder.setOrderCurrencyDescriptionId(
//                aeCurrencyDescriptionMapper.returnCurrencyDescriptionId(orderAmount.getString("currency_code"))
//        );
//
//        //订单到期时间
//        aeStoreOrder.setLeftEndGoodTime(orderDetails.getString("over_time_left"));
//
//        aeStoreOrder.setSellerOperatorLoginId(orderDetails.getString("seller_operator_login_id"));
//        aeStoreOrder.setSellerSignerFullname(orderDetails.getString("seller_signer_fullname"));
//        aeStoreOrder.setOrderStatus(orderDetails.getString("order_status"));
//
//
//        return aeStoreOrder;
//    }

//    /**
//     * 返回数据至Erp
//     *
//     * @param orderId
//     * @return
//     *
//     * 迁移至PullNewOrderFromAeListener
//     */
//    public R<Object> returnErpOrderList(Long orderId) {
//        List<JSONObject> erpSellerOrderList = new ArrayList<>();
//
//        List<AeStoreOrder> returnOrderList = aeStoreOrderMapper.selectList(
//                new LambdaQueryWrapper<AeStoreOrder>().eq(AeStoreOrder::getOrderId, orderId)
//        );
//
//        for (AeStoreOrder aeStoreOrder : returnOrderList) {
//            JSONObject erpSellerOrder = new JSONObject();
//            //获取对应的数据
//            erpSellerOrder.put("sellerLoginId", aeStoreOrder.getSellerOperatorLoginId());
//            erpSellerOrder.put("leftEndGoodTime", aeStoreOrder.getLeftEndGoodTime());
//            erpSellerOrder.put("sellerOperatorLoginId", aeStoreOrder.getSellerOperatorLoginId());
//            erpSellerOrder.put("sellerSignerFullname", aeStoreOrder.getSellerSignerFullname());
//            erpSellerOrder.put("buyerLoginId", aeStoreOrder.getBuyerLoginId());
//            erpSellerOrder.put("orderId", aeStoreOrder.getOrderId());
//            erpSellerOrder.put("bizType", aeStoreOrder.getBizType());
//            erpSellerOrder.put("buyerSignerFullname", aeStoreOrder.getBuyerSignerFullname());
//            erpSellerOrder.put("gmtCreate", aeStoreOrder.getGmtCreate());
//            erpSellerOrder.put("gmtPayTime", aeStoreOrder.getGmtPayTime());
//            erpSellerOrder.put("gmtUpdate", aeStoreOrder.getGmtUpdate());
//            erpSellerOrder.put("orderDetailUrl", aeStoreOrder.getOrderDetailUrl());
//            erpSellerOrder.put("orderStatus", aeStoreOrder.getOrderStatus());
//            erpSellerOrder.put("payCurrencyCode", aeStoreOrder.getPayCurrencyCode());
//            erpSellerOrder.put("payAmount", aeStoreOrder.getSellerOrderAmount());
//            //获取子订单Id列表
//            List<AeStoreChildOrder> childOrderIdList = aeStoreChildOrderMapper.selectChildOrderIdByOrderId(aeStoreOrder.getOrderId());
//            //遍历该List，获取商品List
//            erpSellerOrder.put("sellerChildOrderList", childOrderIdList);
//
//            List<JSONObject> erpSellerOrderProductList = new ArrayList<>();
//            for (AeStoreChildOrder childOrder : childOrderIdList) {
//                //通过子订单id，获取订单商品信息
//                //遍历订单商品id，并存储
//                List<AeStoreOrderProduct> aeStoreOrderProductList = aeStoreOrderProductMapper.selectListByChildOrderId(childOrder.getChildOrderId());
//                for (AeStoreOrderProduct aeStoreOrderProduct : aeStoreOrderProductList) {
//                    JSONObject erpProduct = new JSONObject();
//                    //查找该订单下的子订单的商品详情
//                    if (aeStoreOrderProduct != null) {
//                        erpProduct.put("orderId", aeStoreOrder.getOrderId());
//                        erpProduct.put("productId", aeStoreOrderProduct.getProductId());
//                        erpProduct.put("childId", aeStoreOrderProduct.getChildId());
//                        erpProduct.put("childLogisticsAmount", aeStoreOrderProduct.getChildLogisticsAmount());
//                        erpProduct.put("childLogisticsCurrencyCode", aeStoreOrderProduct.getChildLogisticsCurrencyCode());
//                        erpProduct.put("memo", aeStoreOrderProduct.getMemo());
//                        erpProduct.put("productCount", aeStoreOrderProduct.getProductCount());
//                        erpProduct.put("productId", aeStoreOrderProduct.getProductId());
//                        erpProduct.put("productImgUrl", aeStoreOrderProduct.getProductImgUrl());
//                        erpProduct.put("productName", aeStoreOrderProduct.getProductName());
//                        erpProduct.put("productSnapUrl", aeStoreOrderProduct.getProductSnapUrl());
//                        erpProduct.put("productStandard", aeStoreOrderProduct.getProductStandard());
//                        erpProduct.put("productUnit", aeStoreOrderProduct.getProductUnit());
//                        erpProduct.put("productUnitPrice", aeStoreOrderProduct.getProductUnitPrice());
//                        erpProduct.put("showStatus", aeStoreOrderProduct.getShowStatus());
//                        erpProduct.put("skuCode", aeStoreOrderProduct.getSkuCode());
//                        erpProduct.put("sonOrderStatus", aeStoreOrderProduct.getSonOrderStatus());
//                        erpProduct.put("totalProductAmount", aeStoreOrderProduct.getTotalProductAmount());
//                        erpProduct.put("totalProductCurrencyCode", aeStoreOrderProduct.getTotalProductCurrencyCode());
//                    }
//                    //信息遍历完后，进行存储
//                    erpSellerOrderProductList.add(erpProduct);
//                }
//            }
//            erpSellerOrder.put("sellerOrderProductList", erpSellerOrderProductList);
//            erpSellerOrderList.add(erpSellerOrder);
//        }
//
//        if (erpSellerOrderList.size() > 0) {
//            return R.ok(erpSellerOrderList, "已获取到" + erpSellerOrderList.size() + "条订单");
//        } else {
//            return R.fail("没有新的订单");
//        }
//    }


    // 4.0.0以后废弃
//    @Override
//    public R<Object> getNewOrderFromAe(String sellerId, String accessToken, String createDateStart, String createDateEnd, String currentpage, Integer pageSize) {
//        JSONObject returnOrderList = JSONObject.parseObject(
//                AeApiUtils.sendRequest(
//                        AliExpressInterfaceEnum.findOrderById.getCode(),
//                        "param_aeop_order_query",
//                        "{" +
//                                "\"create_date_start\":\"" + createDateStart + "\"," +
//                                "\"create_date_end\n\":\"" + createDateEnd + "\"," +
//                                "\"current_page\":\"" + currentpage + "\"," +
//                                "\"page_size\":\"" + pageSize + "\"}",
//                        Protocol.TOP,
//                        accessToken
//                )
//        );
//        String orderStr = returnOrderList
//                .getJSONObject("aliexpress_trade_seller_orderlist_get_response")
//                .getJSONObject("result")
//                .getJSONObject("target_list")
//                .getString("aeop_order_item_dto");
//        JSONObject orderJSON = returnOrderList
//                .getJSONObject("aliexpress_trade_seller_orderlist_get_response")
//                .getJSONObject("result")
//                .getJSONObject("target_list")
//                .getJSONObject("aeop_order_item_dto");
//
//        Integer totalCount = returnOrderList
//                .getJSONObject("aliexpress_trade_seller_orderlist_get_response")
//                .getJSONObject("result")
//                .getInteger("total_count");
//
//
//        //新版保存订单
//        getOrderFromAe(orderStr, accessToken);
//
//        if (totalCount != null) {
//            return R.ok("成功获取到" + totalCount + "条新订单");
//        } else {
//            return R.ok("暂无新订单");
//        }
//    }

    // 4.0.0以后废弃
//    private void getOrderFromAe(String orderStr, String accessToken) {
//        //转为list
//        JSONArray jsonArray = JSONArray.parseArray(orderStr);
//
//        if (jsonArray != null) {
//            for (Object aeStoreOrderObject : jsonArray) {
//                JSONObject aeStoreOrderJson = (JSONObject) aeStoreOrderObject;
//                //防重复
//                AeStoreOrder aeStoreOrder = aeStoreOrderMapper.selectByOrderId((Long) aeStoreOrderJson.get("order_id"));
//                if (aeStoreOrder == null) {
//                    aeStoreOrder = new AeStoreOrder();
//                }
//                saveAEOrderDetails(aeStoreOrder, aeStoreOrderJson, accessToken);
//            }
//        }
//    }

    // 4.0.0以后废弃
//    private void saveAEOrderDetails(
//            AeStoreOrder aeStoreOrder,
//            JSONObject aeStoreOrderJson,
//            String accessToken
//    ) {
//        String orderId = aeStoreOrderJson.getString("order_id");
//        //从订单列表中获得信息
//        {
//            //订单类型。（AE_COMMON:普通订单;AE_TRIAL:试用订单;AE_RECHARGE:手机充值订单)
//            aeStoreOrder.setBizType(aeStoreOrderJson.getString("biz_type"));
//
//            //买家全名
//            aeStoreOrder.setBuyerSignerFullname(aeStoreOrderJson.getString("buyer_signer_fullname"));
//            //卖家全名
//            aeStoreOrder.setSellerSignerFullname(aeStoreOrderJson.getString("seller_signer_fullname"));
//            //卖家操作人员的登录id
//            aeStoreOrder.setSellerOperatorLoginId(aeStoreOrderJson.getString("seller_operator_login_id"));
//            //运费佣金比例
//            aeStoreOrder.setLogisitcsEscrowFeeRate(aeStoreOrderJson.getString("logisitcs_escrow_fee_rate"));
//        }
//        //从订单详情里获取信息
//        {
//            JSONObject orderDetails = JSONObject.parseObject(
//                    AeApiUtils.sendRequest(
//                            AliExpressInterfaceEnum.findOrderById.getCode(),
//                            "param1",
//                            "{\"order_id\":" + orderId + "}",
//                            Protocol.TOP,
//                            accessToken
//
//                    )
//            ).getJSONObject("aliexpress_trade_new_redefining_findorderbyid_response").getJSONObject("target");
//
////            aeStoreOrder.setPayAmount();
//
//            //卖家登录ID 店铺cn
//            aeStoreOrder.setSellerLoginId(orderDetails.getString("seller_login_id"));
//            //卖家操作员Ali id
//            aeStoreOrder.setSellerOperatorAliidloginid(orderDetails.getString("seller_operator_aliidloginid"));
//            //支付金额结算币种
//            aeStoreOrder.setSettlementCurrency(orderDetails.getString("settlement_currency"));
//            //是否是货到付款订单
//            aeStoreOrder.setCod(orderDetails.getString("cod"));
//            //买家申请取消订单的原因，仅对取消中的订单有效
//            aeStoreOrder.setCancelRequestReason(orderDetails.getString("cancel_request_reason"));
//
//            //新订单金额，比order_amount更准确，考虑了卖家调价及COD费用。仅限于新订单（7.18-7.31期间创建的部分订单及8.1以后创建的所有订单）。
//            JSONObject newOrderAmount = orderDetails.getJSONObject("new_order_amount");
//            aeStoreOrder.setNewOrderAmount(newOrderAmount.getString("amount"));
//            aeStoreOrder.setNewOrderCurrencyCode(newOrderAmount.getString("currency_code"));
//            aeStoreOrder.setPayCurrencyCode(newOrderAmount.getString("currency_code"));
//
//            //新订单金额，比order_amount更准确，考虑了卖家调价及COD费用。仅限于新订单（7.18-7.31期间创建的部分订单及8.1以后创建的所有订单）。含税价订单，不含税金
//            JSONObject sellerOrderAmount = orderDetails.getJSONObject("seller_order_amount");
//            aeStoreOrder.setSellerOrderAmount(sellerOrderAmount.getString("amount"));
//            aeStoreOrder.setSellerOrderCurrencyCode(sellerOrderAmount.getString("currency_code"));
//            //订单金额
//            JSONObject orderAmount = orderDetails.getJSONObject("order_amount");
//            aeStoreOrder.setOrderAmount(orderAmount.getString("amount"));
//            aeStoreOrder.setOrderCent(orderAmount.getBigDecimal("cent"));
//            aeStoreOrder.setOrderCentFactor(orderAmount.getLong("cent_factor"));
//            //货币描述
//            JSONObject orderCurrency = orderAmount.getJSONObject("currency");
//            aeStoreOrder.setOrderCurrencyDescriptionId(
//                    aeCurrencyDescriptionMapper.returnCurrencyDescriptionId(orderAmount.getString("currency_code"))
//            );
//            //买家信息
//            JSONObject buyerInfo = orderDetails.getJSONObject("buyer_info");
//            //国家/地区
//            aeStoreOrder.setBuyerCountry(buyerInfo.getString("country"));
//            aeStoreOrder.setBuyerLastName(buyerInfo.getString("first_name"));
//            aeStoreOrder.setBuyerFirstName(buyerInfo.getString("last_name"));
//            aeStoreOrder.setBuyerLoginId(buyerInfo.getString("login_id"));
//
//            //订单结束时间(此时间为美国太平洋时间)
//            aeStoreOrder.setGmtTradeEnd(orderDetails.getString("gmt_trade_end"));
//            //订单最后更新时间
//            aeStoreOrder.setGmtUpdate(orderDetails.getString("gmt_modified"));
//            //订单创建时间
//            aeStoreOrder.setGmtCreate(orderDetails.getString("gmt_create"));
//
//            //支付成功时间（与订单列表中gmtPayTime字段意义相同）(此时间为美国太平洋时间)
//            String paySuccess = orderDetails.getString("gmt_pay_success");
//            if (paySuccess != null) {
//                aeStoreOrder.setGmtPayTime(paySuccess);
//            }
//
//            //物流状态：NO_LOGISTICS 无物流信息、等待卖家发货 WAIT_SELLER_SEND_GOODS,卖家部分发货 SELLER_SEND_PART_GOODS,卖家已发货 SELLER_SEND_GOODS,买家已确认收货 BUYER_ACCEPT_GOODS,NO_LOGISTICS
//            aeStoreOrder.setLogisticsStatus(orderDetails.getString("logistics_status"));
//            //冻结状态。(NO_FROZEN:无冻结; IN_FROZEN:冻结中)
//            aeStoreOrder.setFrozenStatus(orderDetails.getString("frozen_status"));
//            //订单状态
//            aeStoreOrder.setOrderStatus(orderDetails.getString("order_status"));
//            //资金状态。(NOT_PAY:未付款; PAY_SUCCESS:付款成功; WAIT_SELLER_CHECK:卖家验款)
//            aeStoreOrder.setFundStatus(orderDetails.getString("fund_status"));
//            //纠纷状态。(NO_ISSUE:无纠纷; IN_ISSUE:纠纷中; END_ISSUE:纠纷结束)
//            aeStoreOrder.setIssueStatus(orderDetails.getString("issue_status"));
//            //买家登录id
//            aeStoreOrder.setBuyerLoginId(orderDetails.getString("buyerloginid"));
//            //当前状态超时日期 （此时间为美国太平洋时间） 过期时间
//            aeStoreOrder.setLeftEndGoodTime(orderDetails.getString("over_time_left"));
//            //备注
//            aeStoreOrder.setMemo(orderDetails.getString("memo"));
//            //结束原因
//            aeStoreOrder.setOrderEndReason(orderDetails.getString("order_end_reason"));
//            aeStoreOrder.setEndReason(orderDetails.getString("order_end_reason"));
//            //买家支付金额(结算币种)
//            //付款方式
//            aeStoreOrder.setPaymentType(orderDetails.getString("payment_type"));
//            //是否手机订单
//            aeStoreOrder.setPhone(orderDetails.getString("is_phone"));
//
//            //更新收货地址
//            {
//                JSONObject receiptAddress = orderDetails.getJSONObject("receipt_address");
//                AeStoreOrderReceiptAddress address = new AeStoreOrderReceiptAddress();
//                address.setZip(receiptAddress.getString("zip"));
//                address.setCountry(receiptAddress.getString("country"));
//                address.setAddress2(receiptAddress.getString("address2"));
//                address.setCity(receiptAddress.getString("city"));
//                address.setContactPerson(receiptAddress.getString("contact_person"));
//                address.setDetailAddress(receiptAddress.getString("detail_address"));
//                address.setMobileNo(receiptAddress.getString("mobile_no"));
//                address.setProvince(receiptAddress.getString("province"));
//                address.setPhoneCountry(receiptAddress.getString("phone_country"));
//                address.setOrderId(aeStoreOrder.getOrderId());
//                address.setOaid(orderDetails.getString("oaid"));
//                //解密收货人信息
//                address = iAeStoreOrderService.tradeSellerOrderDecrypt(address, accessToken);
//                AeStoreOrderReceiptAddress aeStoreOrderReceiptAddressSel = aeStoreOrderReceiptAddressMapper.selectOne(
//                        new LambdaQueryWrapper<AeStoreOrderReceiptAddress>().eq(AeStoreOrderReceiptAddress::getOrderId, aeStoreOrder.getOrderId())
//                );
//                if (aeStoreOrderReceiptAddressSel != null) {
//                    address.setId(aeStoreOrderReceiptAddressSel.getId());
//                }
//                aeStoreOrderReceiptAddressMapper.insertOrUpdate(address);
//            }
//
//        }
//
//        //ERP同步状态 - 未同步
//        aeStoreOrder.setSyncStatus(0);
//    }

}
